# 发送消息
from datetime import datetime, timedelta, time
import time as time_module  # 使用别名
from config_loader import load_config
import pymysql
import requests
import re

from service.handler import get_sign_in_alarms

# 加载配置
cfg = load_config("config.yml")
QX_API_URL = cfg["QX_API_URL"]
TIP_EXAMPLE = cfg["TIP_EXAMPLE"]
PREFIX_STR = cfg["PREFIX_STR"]

# 公共参数
weekday_dict = {'Monday': '一', 'Tuesday': '二', 'Wednesday': '三', 'Thursday': '四', 'Friday': '五', 'Saturday': '六',
                'Sunday': '日'}


# DB创建
def mysql_db():
    conn = pymysql.connect(
        host='101.132.157.214',
        port=3306,
        database='alarm',
        charset='utf8',
        user='root',
        password='Tian201404293'
    )
    return conn


# 发送文本消息【微信公众号】
def make_text_msg_club(from_user, to_user, msg):
    """
    回复文本消息
    * @access public
    * @param  string to_user 接收者微信ID
    * @param  string msg 消息内容
    """
    reply = """
    <xml>
    <ToUserName><![CDATA[{from_user}]]></ToUserName>
    <FromUserName><![CDATA[{to_user}]]></FromUserName>
    <CreateTime>{time}</CreateTime>
    <MsgType><![CDATA[text]]></MsgType>
    <Content><![CDATA[{msg}]]></Content>
    </xml>
    """
    return reply.format(from_user=from_user, to_user=to_user, time=int(time_module.time()), msg=msg)


# 设闹钟设置处理
# 示例：10月27日至11月27日 打卡 每天 8:00 建行CC豆 建行CC豆 www.baidu.com
def set_alarm(conn, alarm_string):
    # 按空格拆分字符串
    parts = alarm_string.split()
    # 获取各部分
    date_range = parts[0]
    alarm_kind = parts[1]  # 闹钟类型: 打卡|抢购
    alarm_frequency = parts[2]  # 闹钟频率
    alarm_time = parts[3]  # 闹钟时间
    alarm_title = parts[4]
    alarm_detail = parts[5]
    alarm_link = parts[6]

    # 解析开始时间和结束时间
    start_date, end_date = date_range.split('至')
    # 对具体时间进行处理，分割小时和分钟

    hour, minute = map(int, alarm_time.split(':'))
    # 转换为一天中的秒数
    final_time = hour * 3600 + minute * 60

    # 获取当前的日期和时间
    now = datetime.now()
    # 将datetime对象转换为字符串
    alarm_time_str = now.strftime('%Y-%m-%d %H:%M:%S')

    # 保存到数据库
    sql = ''' INSERT INTO alarms(start_date, end_date, alarm_time, frequency, alarm_title, alarm_detail, alarm_link, alarm_kind, alarmed_time)
              VALUES(%s, %s, %s, %s, %s, %s, %s, %s, %s) '''
    alarm = (start_date, end_date, final_time, alarm_frequency, alarm_title, alarm_detail, alarm_link, alarm_kind, 0)
    cur = conn.cursor()
    try:
        cur.execute(sql, alarm)
        conn.commit()
    except Exception as e:
        print('闹钟设置失败，err=', str(e))
        return '闹钟设置失败，错误信息：' + str(e)
    return '【设置成功】'


def get_alarms_from_db(conn):
    # 获取当前时间和5分钟后的时间
    now = datetime.now()
    future = now + timedelta(minutes=5)
    # 将当前时间和5分钟后的时间转换为当天的秒数
    now_seconds = (now - now.replace(hour=0, minute=0, second=0, microsecond=0)).total_seconds()
    future_seconds = (future - future.replace(hour=0, minute=0, second=0, microsecond=0)).total_seconds()
    # 从数据库中获取那些在接下来的5分钟内需要提醒的闹钟
    cur = conn.cursor()
    cur.execute(
        "SELECT * FROM alarms WHERE alarm_time >= %s AND alarm_time <= %s AND start_date <= %s AND end_date >= %s AND alarm_kind = 0",
        (now_seconds, future_seconds, now.strftime('%m月%d日'), now.strftime('%m月%d日')))
    alarms = cur.fetchall()

    return alarms


# 从数据库获取今日需要打卡的打卡事件
def get_sign_in_alarms_club(conn, action):
    cur = conn.cursor()
    cur.execute(f"SELECT * FROM alarms WHERE alarm_kind = '{action}'")
    alarms = cur.fetchall()

    return alarms


def handle_set_alarm_club(from_user, to_user, msg):
    # 当收到的消息是时间时，设置定时任务,会先检查消息格式
    pattern = r'\d{1,2}月\d{1,2}日至\d{1,2}月\d{1,2}日 .+'
    reply_to_weixin = ''
    if not re.match(pattern, msg):
        reply_to_weixin = make_text_msg_club(from_user, to_user, '输入格式有误，请按照示例格式输入！')
    else:
        conn = mysql_db()
        # 设置闹钟
        response = set_alarm(conn, msg)
        reply_to_weixin = make_text_msg_club(from_user, to_user, response)

    return reply_to_weixin

# 更新打卡状态
# def update_alarm_status(wxid, fromWxid, msg, user_state):
#     # 连接到数据库
#     conn = mysql_db()
#     cursor = conn.cursor()
#     # 执行查询
#     cursor.execute("UPDATE alarms SET alarmed_time = 1 WHERE id = %s", (msg,))
#     # 提交事务
#     conn.commit()
#     # 检查是否删除成功
#     if cursor.rowcount == 0:
#         send_text_msg_qx(wxid, fromWxid, '更新打卡状态失败')
#     else:
#         send_text_msg_qx(wxid, fromWxid, 'OK OK')
# 更新用户状态
# user_state[fromWxid] = 'normal'


# 处理具体闹钟数据查询
# def handle_alarm_delete(wxid, fromWxid, msg, user_state):
#     # 连接到数据库
#     conn = mysql_db()
#     cursor = conn.cursor()
#     # 执行删除操作
#     cursor.execute("DELETE FROM alarms WHERE id = %s", (msg,))
#     # 提交事务
#     conn.commit()
#     # 检查是否删除成功
#     if cursor.rowcount == 0:
#         send_text_msg_qx(wxid, fromWxid, '删除失败，没有找到指定的ID')
#     else:
#         send_text_msg_qx(wxid, fromWxid, '删除成功')
#     # 更新用户状态
#     user_state[fromWxid] = 'normal'

# 关键字回复：抢购
def alarms_today_club(from_user, to_user, action):
    # 获取今天的日期和星期
    today = datetime.now()
    weekday = '每周' + weekday_dict[today.strftime('%A')]
    date = '每月' + today.strftime('%d') + '号'
    # 获取当前时间
    now = datetime.now()
    # 计算当前时间到第二天00:00的秒数
    seconds_to_midnight = (datetime.combine(now.date() + timedelta(days=1), time(0)) - now).total_seconds()
    # 从数据库中获取所有打卡类型的事件,获取接下来5分钟内需要推送消息的闹钟事件
    conn = mysql_db()
    alarms = get_sign_in_alarms_club(conn, action)
    # 否则，收集所有的闹钟事件
    alarms_str = []
    # 在开头添加一个大标题
    alarms_str.append(f'😂😂😂今日{action}😂😂😂  \n' + PREFIX_STR + '  \n')
    for alarm in alarms:
        # 检查当前时间是否在闹钟时间前的5分钟，并且当前日期在闹钟的开始日期和结束日期之间
        start_date_obj = datetime.strptime(alarm[1], '%m月%d日').date().replace(year=2023)
        end_date_obj = datetime.strptime(alarm[2], '%m月%d日').date().replace(year=2023)
        if start_date_obj <= now.date() <= end_date_obj:
            if alarm[4] == '每天' or alarm[4] == weekday or alarm[4] == date:
                # 将每个闹钟的信息分别添加到列表中
                alarm_info = f"【{alarm[8]}】{alarm[5]}  \n" + f"【内容】{alarm[6]}  \n" + f"【直达】{alarm[7]}  \n" + PREFIX_STR + '  \n'
                alarms_str.append(alarm_info)
            else:
                continue
        else:
            continue
    # 使用join()函数，将列表中的每个元素连接成一个字符串，每个元素之间用换行符分隔
    response = ''.join(alarms_str)
    if len(alarms_str) > 1:
        # server酱推送
        return make_text_msg_club(from_user, to_user, response)
    else:
        response_text = ''
        if action == '抢购':
            response_text = '今天没有抢购任务要做！'
        elif action == '打卡':
            response_text = '今天没有打卡任务要做！'
        elif action == '地铁':
            response_text = '今天没有地铁优惠，你自己看着办吧！'
        return make_text_msg_club(from_user, to_user, response_text)
